﻿using System;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Net;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using System.Linq;
using System.Drawing.Printing;

namespace CashDifferenceReportApp
{
    public partial class CashDifferenceReport : Form
    {
        DataTable dtBranchesAll = null;
        private double ApplicationCashAvailable = 0;
        private double ActualCashAvailable = 0;
        private DateTime SelectedDate = DateTime.Now;

        private const int VERSION = 6;
        private const int APPID = 2;

        int branch = 0;
        //Branch
        //1  - Chandanagar
        //2  - Miyapur
        //3  - Kukatpally
        //4  - Ameerpet
        //5  - JNTU
        //9  - Sangareddy
        //11 - Uppal
        //12 - A.S.Rao Nagar

        string dt = string.Empty;

        #region .Ctr

        public CashDifferenceReport()
        {
            InitializeComponent();

            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-IN");

#if Chandanagar
    branch = 1;
#endif

#if Miyapur
    branch = 2;
#endif

#if Kukatpally
    branch = 3;
#endif

#if Ameerpet
    branch = 4;
#endif

#if JNTU
    branch = 5;
#endif

#if Sangareddy
    branch = 9;
#endif

#if Uppal
    branch = 11;
#endif

#if ASRaoNagar
    branch = 12;
#endif

            /*//Setting TimeLines to Operate the Application
            DateTime currentDate = GetCurrentDateTime();

            //June To Aug
            if (!(currentDate.Month >= 5 && currentDate.Month <= 7))
            {
                MessageBox.Show("Invalid Application Request!!! Contact Administrator.", "Invalid Application", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
                return;
            }*/

            //Validating the version
            if (!DBHelper.ValidateVersion(APPID, VERSION))
            {
                MessageBox.Show("Upgrade to Latest Version !", "Obsolete Version", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
            }

            //Disabling the Tab Control Headers
            tabMainCtrl.Appearance = TabAppearance.FlatButtons;
            tabMainCtrl.ItemSize = new Size(0, 1);
            tabMainCtrl.SizeMode = TabSizeMode.Fixed;

            dpDateBulk.MaxDate = dpDate.MaxDate = dtpCancelledBills.MaxDate = dtDiscount.MaxDate = dtpCakeReport.MaxDate = dtpCakeDeliveryReport.MaxDate = DateTime.Now;

            if (dtBranchesAll == null)
            {
                dtBranchesAll = DBHelper.GetBranches();
                dtBranchesAll.Rows.Add(0, "All");
            }
            cmbBranch.DataSource = dtBranchesAll;
            cmbBranch.DisplayMember = "BranchName";
            cmbBranch.ValueMember = "BranchID";

            cmbBranchCancelledBills.DataSource = dtBranchesAll;
            cmbBranchCancelledBills.DisplayMember = "BranchName";
            cmbBranchCancelledBills.ValueMember = "BranchID";

            cmbDiscountBranch.DataSource = dtBranchesAll;
            cmbDiscountBranch.DisplayMember = "BranchName";
            cmbDiscountBranch.ValueMember = "BranchID";

            cmbCakeBranches.DataSource = dtBranchesAll;
            cmbCakeBranches.DisplayMember = "BranchName";
            cmbCakeBranches.ValueMember = "BranchID";

            cmbCakeDeliveryReport.DataSource = dtBranchesAll;
            cmbCakeDeliveryReport.DisplayMember = "BranchName";
            cmbCakeDeliveryReport.ValueMember = "BranchID";

            cmbBranchBulk.DataSource = dtBranchesAll;
            cmbBranchBulk.DisplayMember = "BranchName";
            cmbBranchBulk.ValueMember = "BranchID";

            cmbBranch.SelectedValue = branch;
            cmbBranchCancelledBills.SelectedValue = branch;
            cmbDiscountBranch.SelectedValue = branch;
            cmbCakeBranches.SelectedValue = branch;
            cmbCakeDeliveryReport.SelectedValue = branch;

            switch (branch)
            {
                case 1:
                    lblBranch.Text = "Chandanagar";
                    lblHeading.Text = "Chandanagar Sales Details";
                    break;

                case 2:
                    lblBranch.Text = "Miyapur";
                    lblHeading.Text = "Miyapur Sales Details";
                    break;

                case 3:
                    lblBranch.Text = "Kukatpally";
                    lblHeading.Text = "Kukatpally Sales Details";
                    break;

                case 4:
                    lblBranch.Text = "Ameerpet";
                    lblHeading.Text = "Ameerpet Sales Details";
                    break;

                case 5:
                    lblBranch.Text = "JNTU";
                    lblHeading.Text = "JNTU Sales Details";
                    break;

                case 9:
                    lblBranch.Text = "Sangareddy";
                    lblHeading.Text = "Sangareddy Sales Details";
                    break;

                case 11:
                    lblBranch.Text = "Uppal";
                    lblHeading.Text = "Uppal Sales Details";
                    break;

                case 12:
                    lblBranch.Text = "A.S.Rao Nagar";
                    lblHeading.Text = "A.S.Rao Nagar Sales Details";
                    break;
            }
        }

        #endregion

        #region Private Methods

        private DateTime GetCurrentDateTime()
        {
            try
            {
                WebRequest request = WebRequest.Create(@"http://developer.yahooapis.com/TimeService/V1/getTime?appid=Test");
                // request.Proxy = new WebProxy("PROXYSERVERNAME", 8080); // You may or may not need this 
                WebResponse response = request.GetResponse();

                Double currentTimeStamp = 0;
                using (Stream stream = response.GetResponseStream())
                {
                    using (XmlTextReader xmlReader = new XmlTextReader(stream))
                    {
                        while (xmlReader.Read())
                        {
                            switch (xmlReader.NodeType)
                            {
                                case XmlNodeType.Element:
                                    if (xmlReader.Name == "Timestamp")
                                    {
                                        currentTimeStamp = Convert.ToDouble(xmlReader.ReadInnerXml());
                                    }
                                    break;
                            }
                        }

                        xmlReader.Close();
                    }
                }

                DateTime yahooDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
                return yahooDateTime.AddSeconds(currentTimeStamp).AddHours(5).AddMinutes(30);
            }
            catch (Exception ex)
            {
                WriteToEventViewer("Couldn't get the current time from internet. " + ex.Message);
                return DateTime.Now;
            }
        }

        private void WriteToEventViewer(string message)
        {
            try
            {
                if (!EventLog.SourceExists("KSBakery"))
                    EventLog.CreateEventSource("KSBakery", "KSBakery");
                EventLog.WriteEntry("KSBakery", message, EventLogEntryType.Error);
            }
            catch (Exception)
            { }
        }

        #endregion

        #region Financial Report

        private void btnCashDifferenceReport_Click(object sender, EventArgs e)
        {
            try
            {
                tabMainCtrl.SelectTab(1);

                dpDate.Value = SelectedDate;
                dgvIndividualSales.DataSource = null;

                lblPOSSales.Text = "POS Sales: ";
                lblCakeSales.Text = "Cake Sales: ";

                lblCakeAdvances.Text = "Advances: ";
                lblCakeIdealBalances.Text = "Ideal Balances: ";
                lblCakeActualBalances.Text = "Actual Balances: ";

                lblDiscount.Text = "Discount: ";
                lblTotalSales.Text = "Total Sales: ";
                lblExpenditure.Text = "Expenses: ";
                lblSodexho.Text = "Sodexho Sales: ";
                lblCard.Text = "Card Sales: ";
                lblSalariesAppDetails.Text = "Emp Advance/Bill Amounts: ";
                lblCreditNoteBills.Text = "Credit Note Amount: ";
                lblCashAvailable.Text = "Cash Available: ";
                lblBulkOrders.Text = "Bulk Orders: ";

                lblBulkOrderAdvances.Text = "Advances: ";
                lblBulkOrderIdealBalances.Text = "Ideal Balances: ";
                lblBulkOrderActualBalances.Text = "Actual Balances: ";
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnFinancialReport_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                SelectedDate = dpDate.Value;
                if (cmbBranch.SelectedValue.ToString() == "0")
                {
                    MessageBox.Show("Connecting to Branches cannot fetch Complete Data. Please change the Criteria.", "Invalid Criteria", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                dgvIndividualSales.DataSource = null;

                lblPOSSales.Text = "POS Sales: ";
                lblCakeSales.Text = "Cake Sales: ";

                lblCakeAdvances.Text = "Advances: ";
                lblCakeIdealBalances.Text = "Ideal Balances: ";
                lblCakeActualBalances.Text = "Actual Balances: ";

                lblDiscount.Text = "Discount: ";
                lblTotalSales.Text = "Total Sales: ";
                lblExpenditure.Text = "Expenses: ";
                lblSodexho.Text = "Sodexho Sales: ";
                lblCard.Text = "Card Sales: ";
                lblSalariesAppDetails.Text = "Emp Advance/Bill Amounts: ";
                lblCreditNoteBills.Text = "Credit Note Amount: ";
                lblCashAvailable.Text = "Cash Available: ";
                lblBulkOrders.Text = "Bulk Orders: ";

                lblBulkOrderAdvances.Text = "Advances: ";
                lblBulkOrderIdealBalances.Text = "Ideal Balances: ";
                lblBulkOrderActualBalances.Text = "Actual Balances: ";

                DataSet dsResult = DBHelper.GetFinancialReport(dpDate.Value, cmbBranch.SelectedValue.ToString());

                dt = dpDate.Value.ToString("dd-MMM-yyyy");

                double cakeSales = 0d;

                double cakeAdvances = 0d;
                double cakeIdealBalances = 0d;
                double cakeActualBalances = 0d;

                double discounts = 0d;
                double totalSales = 0d;
                double expenseAmt = 0d;
                double sodexhoAmt = 0d;
                double creditCardAmt = 0d;
                double salariesAmt = 0d;
                double creditNoteAmount = 0d;
                double bulkOrderAmt = 0d;

                double boAdvances = 0d;
                double boIdealBalances = 0d;
                double boActualBalances = 0d;

                if (dsResult != null)
                {
                    //Empty Row
                    dsResult.Tables[0].Rows.Add(dsResult.Tables[0].NewRow());

                    //POS Sales
                    DataRow drSales = dsResult.Tables[0].NewRow();
                    drSales[1] = "POS SALES";
                    if (dsResult.Tables[1].Rows[0]["POSSales"] != System.DBNull.Value)
                    {
                        drSales[3] = dsResult.Tables[1].Rows[0]["POSSales"].ToString();
                    }
                    else
                    {
                        drSales[3] = 0;
                    }
                    dsResult.Tables[0].Rows.Add(drSales);

                    //Cake Sales
                    double tmpValue = 0d;

                    if (double.TryParse(dsResult.Tables[2].Rows[0]["Advance"].ToString(), out tmpValue))
                    {
                        double discount = 0d;
                        double.TryParse(dsResult.Tables[2].Rows[0]["CakeDiscounts"].ToString(), out discount);

                        cakeAdvances = tmpValue - discount;
                        cakeSales += tmpValue - discount;
                    }
                    if (double.TryParse(dsResult.Tables[3].Rows[0]["Balance"].ToString(), out tmpValue))
                    {
                        cakeIdealBalances = tmpValue;
                        //cakeSales += tmpValue;
                    }

                    if (dsResult.Tables[14] != null && dsResult.Tables[14].Rows.Count > 0)
                    {
                        double val = 0d;
                        foreach (DataRow row in dsResult.Tables[14].Rows)
                        {
                            double.TryParse(row["CakeBalances"].ToString(), out val);
                            cakeActualBalances += val;
                        }
                    }
                    cakeSales += cakeActualBalances;

                    DataRow drCakeSales = dsResult.Tables[0].NewRow();
                    drCakeSales[1] = "TOTAL CAKE SALES";
                    drCakeSales[3] = cakeSales.ToString();
                    dsResult.Tables[0].Rows.Add(drCakeSales);

                    DataRow drCakeAdvances = dsResult.Tables[0].NewRow();
                    drCakeAdvances[1] = "CAKE ADVANCES";
                    drCakeAdvances[3] = cakeAdvances.ToString();
                    dsResult.Tables[0].Rows.Add(drCakeAdvances);

                    DataRow drCakeIdealBalances = dsResult.Tables[0].NewRow();
                    drCakeIdealBalances[1] = "CAKE IDEAL BALANCES";
                    drCakeIdealBalances[3] = cakeIdealBalances.ToString();
                    dsResult.Tables[0].Rows.Add(drCakeIdealBalances);

                    DataRow drCakeActualBalances = dsResult.Tables[0].NewRow();
                    drCakeActualBalances[1] = "CAKE ACTUAL BALANCES";
                    drCakeActualBalances[3] = cakeActualBalances.ToString();
                    dsResult.Tables[0].Rows.Add(drCakeActualBalances);

                    //Vendor Sales
                    double vendorSales = 0d;

                    double.TryParse(dsResult.Tables[7].Rows[0]["VendorSales"].ToString(), out vendorSales);
                    DataRow drVendorSales = dsResult.Tables[0].NewRow();
                    drVendorSales[1] = "VENDOR SALES";
                    drVendorSales[3] = vendorSales.ToString();
                    dsResult.Tables[0].Rows.Add(drVendorSales);

                    //Bulk Orders
                    if (dsResult.Tables[8] != null && dsResult.Tables[8].Rows.Count > 0)
                    {
                        double.TryParse(dsResult.Tables[8].Rows[0]["BulkOrderAdvance"].ToString(), out tmpValue);
                        boAdvances = tmpValue;
                        bulkOrderAmt += tmpValue;
                    }

                    if (dsResult.Tables[9] != null && dsResult.Tables[9].Rows.Count > 0)
                    {
                        double.TryParse(dsResult.Tables[9].Rows[0]["BulkOrderBalance"].ToString(), out tmpValue);
                        boIdealBalances = tmpValue;
                        //bulkOrderAmt += tmpValue;
                    }

                    if (dsResult.Tables[16] != null && dsResult.Tables[16].Rows.Count > 0)
                    {
                        double val = 0d;
                        foreach (DataRow row in dsResult.Tables[16].Rows)
                        {
                            double.TryParse(row["Balance"].ToString(), out val);
                            boActualBalances += val;
                        }
                    }
                    bulkOrderAmt += boActualBalances;

                    DataRow drBulkOrder = dsResult.Tables[0].NewRow();
                    drBulkOrder[1] = "BULK ORDERS";
                    drBulkOrder[3] = bulkOrderAmt.ToString();
                    dsResult.Tables[0].Rows.Add(drBulkOrder);

                    //Discount
                    tmpValue = 0d;

                    if (dsResult.Tables[1].Rows.Count > 0)
                    {
                        if (double.TryParse(dsResult.Tables[1].Rows[0]["POSDiscounts"].ToString(), out tmpValue))
                            discounts += tmpValue;
                    }

                    double cakeDiscounts = 0d;
                    if (dsResult.Tables[2].Rows.Count > 0)
                    {
                        if (double.TryParse(dsResult.Tables[2].Rows[0]["CakeDiscounts"].ToString(), out cakeDiscounts))
                            discounts += cakeDiscounts;
                    }

                    DataRow drDiscount = dsResult.Tables[0].NewRow();
                    drDiscount[1] = "DISCOUNT";
                    drDiscount[3] = discounts;
                    dsResult.Tables[0].Rows.Add(drDiscount);

                    //Total Sales
                    tmpValue = 0d;

                    if (dsResult.Tables[1].Rows.Count > 0)
                    {
                        if (double.TryParse(dsResult.Tables[1].Rows[0]["POSSales"].ToString(), out tmpValue))
                        {
                            totalSales += tmpValue;
                        }
                    }
                    totalSales += cakeSales;
                    totalSales += vendorSales;
                    totalSales += bulkOrderAmt;
                    //totalSales += creditNoteAmount;

                    DataRow drTotalSales = dsResult.Tables[0].NewRow();
                    drTotalSales[1] = "TOTAL SALES";
                    drTotalSales[3] = (totalSales - discounts + creditNoteAmount).ToString();
                    dsResult.Tables[0].Rows.Add(drTotalSales);

                    //Expense Amounts
                    tmpValue = 0d;

                    if (dsResult.Tables[4].Rows.Count > 0)
                    {
                        if (double.TryParse(dsResult.Tables[4].Rows[0]["ExpenseAmount"].ToString(), out tmpValue))
                            expenseAmt = tmpValue;
                    }

                    DataRow drExpense = dsResult.Tables[0].NewRow();
                    drExpense[1] = "EXPENSE AMOUNT";
                    drExpense[3] = expenseAmt.ToString();
                    dsResult.Tables[0].Rows.Add(drExpense);

                    //Sodexho Amount
                    tmpValue = 0d;

                    if (dsResult.Tables[5].Rows.Count > 0)
                    {
                        if (double.TryParse(dsResult.Tables[5].Rows[0]["SodexhoAmount"].ToString(), out tmpValue))
                            sodexhoAmt = tmpValue;
                    }

                    DataRow drSodexho = dsResult.Tables[0].NewRow();
                    drSodexho[1] = "SODEXHO AMOUNT";
                    drSodexho[3] = sodexhoAmt.ToString();
                    dsResult.Tables[0].Rows.Add(drSodexho);

                    //CreditCard Amount
                    tmpValue = 0d;

                    if (dsResult.Tables[5].Rows.Count > 0)
                    {
                        if (double.TryParse(dsResult.Tables[5].Rows[0]["CreditCardAmount"].ToString(), out tmpValue))
                            creditCardAmt = tmpValue;
                    }

                    DataRow drCard = dsResult.Tables[0].NewRow();
                    drCard[1] = "CREDITCARD AMOUNT";
                    drCard[3] = creditCardAmt.ToString();
                    dsResult.Tables[0].Rows.Add(drCard);

                    //Get Advances & Bill from Salaries Application - By Cashier
                    //salariesAmt = DBHelper.GetEmpAdvancesandBills(dpDate.Value, cmbBranch.SelectedValue.ToString());
                    DataSet dsAdvancesAndBills = DBHelper.GetEmpAdvancesandBills(dpDate.Value, cmbBranch.SelectedValue.ToString());
                    try
                    {
                        salariesAmt = double.Parse(dsAdvancesAndBills.Tables[0].Rows[0]["EmployeeDebitAmount"].ToString());
                    }
                    catch (Exception)
                    {
                        salariesAmt = 0d;
                    }

                    DataRow drSalariesApp = dsResult.Tables[0].NewRow();
                    drSalariesApp[1] = "EMP ADVANCES/BILLS";
                    drSalariesApp[3] = salariesAmt.ToString();
                    dsResult.Tables[0].Rows.Add(drSalariesApp);

                    //Credit Note Amount
                    if (dsResult.Tables[6].Rows.Count > 0)
                    {
                        if (double.TryParse(dsResult.Tables[6].Rows[0]["CreditNoteAmount"].ToString(), out tmpValue))
                            creditNoteAmount = tmpValue;
                    }

                    DataRow drCreditNoteAmount = dsResult.Tables[0].NewRow();
                    drCreditNoteAmount[1] = "CREDIT NOTES AMOUNT";
                    drCreditNoteAmount[3] = creditNoteAmount;
                    dsResult.Tables[0].Rows.Add(drCreditNoteAmount);

                    //Available Cash
                    DataRow drAvailableCash = dsResult.Tables[0].NewRow();
                    drAvailableCash[1] = "AVAILABLE CASH";
                    //drAvailableCash[3] = Math.Round(totalSales - discounts - expenseAmt - sodexhoAmt - creditCardAmt - salariesAmt - creditNoteAmount, 2);
                    drAvailableCash[3] = Math.Round(totalSales - discounts - expenseAmt - sodexhoAmt - creditCardAmt - salariesAmt, 2);
                    dsResult.Tables[0].Rows.Add(drAvailableCash);

                    //dgFinancialReport.DataSource = dsResult.Tables[0];
                    //dgFinancialReport.Columns[0].Width = 80;
                    //dgFinancialReport.Columns[1].Width = 170;
                    //dgFinancialReport.Columns[2].Width = 70;
                    //dgFinancialReport.Columns[3].Width = 100;

                    lblPOSSales.Text = "POS Sales: " + dsResult.Tables[1].Rows[0]["POSSales"].ToString();
                    lblCakeSales.Text = "Cake Sales: " + cakeSales.ToString();

                    lblCakeAdvances.Text = "Advances: " + cakeAdvances.ToString();
                    lblCakeIdealBalances.Text = "Ideal Balances: " + cakeIdealBalances.ToString();
                    lblCakeActualBalances.Text = "Actual Balances: " + cakeActualBalances.ToString();

                    lblDiscount.Text = "Discount: " + discounts.ToString();
                    lblTotalSales.Text = "Total Sales: " + (totalSales - discounts + creditNoteAmount).ToString();
                    lblExpenditure.Text = "Expenses: " + expenseAmt.ToString();
                    lblSodexho.Text = "Sodexho Sales: " + sodexhoAmt.ToString();
                    lblCard.Text = "Card Sales: " + creditCardAmt.ToString();
                    lblSalariesAppDetails.Text = "Emp Advance/Bill Amounts: " + salariesAmt.ToString();
                    lblCreditNoteBills.Text = "Credit Note Amount: " + creditNoteAmount.ToString();
                    //ApplicationCashAvailable = Math.Round(totalSales - discounts - expenseAmt - sodexhoAmt - creditCardAmt - salariesAmt - creditNoteAmount, 2);
                    ApplicationCashAvailable = Math.Round(totalSales - discounts - expenseAmt - sodexhoAmt - creditCardAmt - salariesAmt, 2);
                    lblCashAvailable.Text = "Cash Available: " + ApplicationCashAvailable.ToString();
                    lblBulkOrders.Text = "Bulk Orders: " + bulkOrderAmt.ToString();

                    lblBulkOrderAdvances.Text = "Advances: " + boAdvances.ToString();
                    lblBulkOrderIdealBalances.Text = "Ideal Balances: " + boIdealBalances.ToString();
                    lblBulkOrderActualBalances.Text = "Actual Balances: " + boActualBalances.ToString();

                    //For Printing Purpose
                    Storage.CakeSales = cakeSales;

                    Storage.CakeAdvances = cakeAdvances;
                    Storage.CakeIdealBalances = cakeIdealBalances;
                    Storage.CakeActualBalances = cakeActualBalances;

                    Storage.Discount = discounts;
                    Storage.BulkOrders = bulkOrderAmt;
                    Storage.Expenses = expenseAmt;
                    Storage.SodexhoSales = sodexhoAmt;
                    Storage.CardSales = creditCardAmt;
                    Storage.EmpAdvanceAndBillAmounts = salariesAmt;
                    Storage.CreditNoteAmount = creditNoteAmount;
                    Storage.CashAvailable = ApplicationCashAvailable;

                    if (cmbBranch.SelectedValue.ToString() != "0")
                    {
                        DataRow drRow = DBHelper.GetActualAmount(dpDate.Value, cmbBranch.SelectedValue.ToString());
                        if (drRow != null)
                        {
                            ActualCashAvailable = double.Parse(drRow[0].ToString());
                            //lblDifference.Text = Math.Round(double.Parse(drRow[1].ToString()), 0).ToString();

                            //Actual Available Cash
                            DataRow drActualCashAvailable = dsResult.Tables[0].NewRow();
                            drActualCashAvailable[1] = "ACTUAL CASH AVAILABLE";
                            drActualCashAvailable[3] = ActualCashAvailable;
                            dsResult.Tables[0].Rows.Add(drActualCashAvailable);

                            //Difference
                            DataRow drDifference = dsResult.Tables[0].NewRow();
                            drDifference[1] = "DIFFERENCE";
                            //drDifference[3] = lblDifference.Text;
                            dsResult.Tables[0].Rows.Add(drDifference);
                        }
                        else
                        {
                            ActualCashAvailable = 0;
                            //lblDifference.Text = string.Empty;
                        }
                        //txtActualAmount.Enabled = true;
                        //btnEditAvailableCash.Enabled = true;
                    }
                    else
                    {
                        ActualCashAvailable = 0;
                        //txtActualAmount.Enabled = false;
                        //btnEditAvailableCash.Enabled = false;
                    }

                    //if (ActualCashAvailable != 0)
                    //{
                    //    txtActualAmount.Text = ActualCashAvailable.ToString();
                    //    txtActualAmount.ReadOnly = true;
                    //    btnSaveActualCash.Enabled = false;
                    //    btnEditAvailableCash.Enabled = true;
                    //    //btnSaveActualCash.Enabled = true;
                    //}
                    //else
                    //{
                    //    txtActualAmount.Clear();
                    //    txtActualAmount.ReadOnly = false;
                    //    btnSaveActualCash.Enabled = true;
                    //    btnEditAvailableCash.Enabled = false;
                    //    //btnSaveActualCash.Enabled = false;
                    //}

                    DataTable dtIndSales = new DataTable();
                    dtIndSales.Columns.Add("ID", typeof(string));
                    dtIndSales.Columns.Add("Cashier", typeof(string));
                    dtIndSales.Columns.Add("Sales", typeof(string));
                    dtIndSales.Columns.Add("Discounts", typeof(string));

                    dtIndSales.Columns.Add("CakeAdvances", typeof(string)); //4
                    dtIndSales.Columns.Add("CakeDiscounts", typeof(string));//5
                    dtIndSales.Columns.Add("CakeBalances", typeof(string)); //6

                    dtIndSales.Columns.Add("BOAdvances", typeof(string));   //7 -
                    dtIndSales.Columns.Add("BOBalances", typeof(string));   //8 -

                    dtIndSales.Columns.Add("Expenses", typeof(string));     //9     4
                    dtIndSales.Columns.Add("Sodexho", typeof(string));      //10     5
                    dtIndSales.Columns.Add("CreditCard", typeof(string));   //11     6
                    dtIndSales.Columns.Add("Advance/Bills", typeof(string));//12    7
                    dtIndSales.Columns.Add("CashAvailable", typeof(string));//13    8
                    dtIndSales.Columns.Add("CashInHand", typeof(string));   //14    9
                    dtIndSales.Columns.Add("Difference", typeof(string));   //15    10

                    //Cashier Wise POS Sales and POS Discounts - 10
                    foreach (DataRow row in dsResult.Tables[10].Rows)
                    {
                        DataRow r = dtIndSales.NewRow();
                        r["ID"] = row[0];
                        r["Cashier"] = row[1];
                        r["Sales"] = row[2];
                        r["Discounts"] = row[3];
                        dtIndSales.Rows.Add(r);
                    }

                    //CakeAdvances, CakeDiscounts
                    foreach (DataRow mainRow in dsResult.Tables[13].Rows)
                    {
                        foreach (DataRow row in dtIndSales.Rows)
                        {
                            if (mainRow["Cashier"].ToString().Trim() == row["ID"].ToString().Trim())
                            {
                                row["CakeAdvances"] = mainRow["Advance"];
                                row["CakeDiscounts"] = mainRow["CakeDiscounts"];
                            }
                        }
                    }

                    //CakeBalances
                    foreach (DataRow mainRow in dsResult.Tables[14].Rows)
                    {
                        foreach (DataRow row in dtIndSales.Rows)
                        {
                            if (mainRow["Cashier"].ToString().Trim() == row["ID"].ToString().Trim())
                            {
                                row["CakeBalances"] = mainRow["CakeBalances"];
                            }
                        }
                    }

                    //Bulk Order Advances - 15
                    foreach (DataRow mainRow in dsResult.Tables[15].Rows)
                    {
                        foreach (DataRow row in dtIndSales.Rows)
                        {
                            if (mainRow["Cashier"].ToString().Trim() == row["ID"].ToString().Trim())
                            {
                                row["BOAdvances"] = mainRow["Advance"];
                            }
                        }
                    }

                    //Bulk Order Balances - 16
                    foreach (DataRow mainRow in dsResult.Tables[16].Rows)
                    {
                        foreach (DataRow row in dtIndSales.Rows)
                        {
                            if (mainRow["Cashier"].ToString().Trim() == row["ID"].ToString().Trim())
                            {
                                row["BOBalances"] = mainRow["Balance"];
                            }
                        }
                    }

                    //Cashier Wise Expenses - 11
                    foreach (DataRow mainRow in dsResult.Tables[11].Rows)
                    {
                        foreach (DataRow row in dtIndSales.Rows)
                        {
                            if (mainRow["Cashier"].ToString().Trim() == row["ID"].ToString().Trim())
                            {
                                row["Expenses"] = mainRow["ExpenseAmount"];
                            }
                        }
                    }

                    //Cashier Wise Sodexho & Credit Card Amounts - 12
                    foreach (DataRow mainRow in dsResult.Tables[12].Rows)
                    {
                        foreach (DataRow row in dtIndSales.Rows)
                        {
                            if (mainRow["Cashier"].ToString().Trim() == row["ID"].ToString().Trim())
                            {
                                row["Sodexho"] = mainRow["SodexhoAmount"];
                                row["CreditCard"] = mainRow["CreditCardAmount"];
                            }
                        }
                    }

                    //Employees Advances & Bills - dsAdvancesAndBills
                    if (dsAdvancesAndBills != null && dsAdvancesAndBills.Tables != null && dsAdvancesAndBills.Tables.Count > 1)
                    {
                        foreach (DataRow mainRow in dsAdvancesAndBills.Tables[1].Rows)
                        {
                            foreach (DataRow row in dtIndSales.Rows)
                            {
                                if (mainRow["Cashier"].ToString().Trim() == row["ID"].ToString().Trim())
                                {
                                    row["Advance/Bills"] = mainRow["EmployeeDebitAmount"];
                                }
                            }
                        }
                    }

                    //Calculating Total Available Amount
                    foreach (DataRow row in dtIndSales.Rows)
                    {
                        //POS Sales
                        double sales = 0d;
                        double.TryParse(row[2].ToString(), out sales);
                        if (sales == 0)
                        {
                            row[2] = string.Empty;
                        }

                        //POS Discounts
                        double discs = 0d;
                        double.TryParse(row[3].ToString(), out discs);
                        if (discs == 0)
                        {
                            row[3] = string.Empty;
                        }

                        double cakeAdvance = 0d;
                        double.TryParse(row[4].ToString(), out cakeAdvance);
                        if (cakeAdvance == 0)
                        {
                            row[4] = string.Empty;
                        }

                        double cakeDisc = 0d;
                        double.TryParse(row[5].ToString(), out cakeDisc);
                        if (cakeDisc == 0)
                        {
                            row[5] = string.Empty;
                        }

                        double cakeBal = 0d;
                        double.TryParse(row[6].ToString(), out cakeBal);
                        if (cakeBal == 0)
                        {
                            row[6] = string.Empty;
                        }

                        //Bulk Orders
                        double boAdv = 0d;
                        double.TryParse(row[7].ToString(), out boAdv);
                        if (boAdv == 0)
                        {
                            row[7] = string.Empty;
                        }

                        double boBal = 0d;
                        double.TryParse(row[8].ToString(), out boBal);
                        if (boBal == 0)
                        {
                            row[8] = string.Empty;
                        }

                        //+3

                        //Expenses
                        double expen = 0d;
                        double.TryParse(row[9].ToString(), out expen);
                        if (expen == 0)
                        {
                            row[9] = string.Empty;
                        }

                        //Sodexho
                        double sodexho = 0d;
                        double.TryParse(row[10].ToString(), out sodexho);

                        if (sodexho == 0)
                            row[10] = string.Empty;

                        //CreditCard
                        double credit = 0d;
                        double.TryParse(row[11].ToString(), out credit);

                        if (credit == 0)
                            row[11] = string.Empty;

                        //Advances & Bills
                        double advan = 0d;
                        double.TryParse(row[12].ToString(), out advan);

                        if (advan == 0)
                            row[12] = string.Empty;

                        row[13] = (sales - discs - expen - sodexho - credit - advan + cakeAdvance - cakeDisc + cakeBal + boAdv + boBal).ToString();
                    }

                    /*//Cake Sales
                    DataRow cakeRow = dtIndSales.NewRow();
                    cakeRow[0] = string.Empty;
                    cakeRow[1] = "Cake Sales";
                    cakeRow[2] = cakeSales.ToString();
                    cakeRow[3] = cakeDiscounts.ToString();
                    cakeRow[4] = string.Empty;
                    cakeRow[5] = string.Empty;
                    cakeRow[6] = string.Empty;
                    bulkRow[7] = string.Empty;
                    bulkRow[8] = string.Empty;
                    bulkRow[9] = string.Empty;
                    cakeRow[10] = string.Empty;
                    cakeRow[11] = (cakeSales - cakeDiscounts).ToString();
                    dtIndSales.Rows.Add(cakeRow);

                    //Bulk Orders
                    DataRow bulkRow = dtIndSales.NewRow();
                    bulkRow[0] = string.Empty;
                    bulkRow[1] = "Bulk Sales";
                    bulkRow[2] = bulkOrderAmt.ToString();
                    bulkRow[3] = string.Empty;
                    bulkRow[4] = string.Empty;
                    bulkRow[5] = string.Empty;
                    bulkRow[6] = string.Empty;
                    bulkRow[7] = string.Empty;
                    bulkRow[8] = string.Empty;
                    bulkRow[9] = string.Empty;
                    bulkRow[10] = string.Empty;
                    bulkRow[11] = bulkOrderAmt.ToString();
                    dtIndSales.Rows.Add(bulkRow);*/

                    //Get Actual Amounts If Entered
                    DataTable dsActuals = DBHelper.GetActuals(dpDate.Value, cmbBranch.SelectedValue.ToString(), dtIndSales);
                    if (dsActuals != null)
                    {
                        foreach (DataRow row in dtIndSales.Rows)
                        {
                            DataRow[] rows = dsActuals.Select("Type = '" + row["Cashier"].ToString() + "'");
                            if (rows != null && rows.Count() > 0)
                            {
                                row["CashInHand"] = rows[0][1].ToString();
                                row["Difference"] = rows[0][2].ToString();
                            }
                        }
                    }
                    SelectedDate = dpDate.Value;



                    dgvIndividualSales.DataSource = dtIndSales;

                    dgvIndividualSales.Columns[0].ReadOnly = true;
                    dgvIndividualSales.Columns[1].ReadOnly = true;
                    dgvIndividualSales.Columns[2].ReadOnly = true;
                    dgvIndividualSales.Columns[3].ReadOnly = true;
                    dgvIndividualSales.Columns[4].ReadOnly = true;
                    dgvIndividualSales.Columns[5].ReadOnly = true;
                    dgvIndividualSales.Columns[6].ReadOnly = true;
                    dgvIndividualSales.Columns[7].ReadOnly = true;
                    dgvIndividualSales.Columns[8].ReadOnly = true;
                    dgvIndividualSales.Columns[9].ReadOnly = true;
                    dgvIndividualSales.Columns[10].ReadOnly = true;
                    dgvIndividualSales.Columns[11].ReadOnly = true;
                    dgvIndividualSales.Columns[12].ReadOnly = true;
                    dgvIndividualSales.Columns[13].ReadOnly = true;
                    dgvIndividualSales.Columns[15].ReadOnly = true;

                    dgvIndividualSales.Columns[0].Width = 50;
                    dgvIndividualSales.Columns[1].Width = 120;
                    dgvIndividualSales.Columns[2].Width = 87;
                    dgvIndividualSales.Columns[3].Width = 87;
                    dgvIndividualSales.Columns[4].Width = 87;
                    dgvIndividualSales.Columns[5].Width = 87;
                    dgvIndividualSales.Columns[6].Width = 87;
                    dgvIndividualSales.Columns[7].Width = 87;
                    dgvIndividualSales.Columns[8].Width = 87;
                    dgvIndividualSales.Columns[9].Width = 87;
                    dgvIndividualSales.Columns[10].Width = 87;
                    dgvIndividualSales.Columns[11].Width = 87;
                    dgvIndividualSales.Columns[12].Width = 87;
                    dgvIndividualSales.Columns[13].Width = 87;
                    dgvIndividualSales.Columns[14].Width = 87;
                    dgvIndividualSales.Columns[15].Width = 87;

                    dgvIndividualSales.Columns[0].HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Regular, GraphicsUnit.Pixel);
                    dgvIndividualSales.Columns[1].HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Regular, GraphicsUnit.Pixel);
                    dgvIndividualSales.Columns[2].HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Regular, GraphicsUnit.Pixel);
                    dgvIndividualSales.Columns[3].HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Regular, GraphicsUnit.Pixel);
                    dgvIndividualSales.Columns[4].HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Regular, GraphicsUnit.Pixel);
                    dgvIndividualSales.Columns[5].HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Regular, GraphicsUnit.Pixel);
                    dgvIndividualSales.Columns[6].HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Regular, GraphicsUnit.Pixel);
                    dgvIndividualSales.Columns[7].HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Regular, GraphicsUnit.Pixel);
                    dgvIndividualSales.Columns[8].HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Regular, GraphicsUnit.Pixel);
                    dgvIndividualSales.Columns[9].HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Regular, GraphicsUnit.Pixel);
                    dgvIndividualSales.Columns[10].HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Regular, GraphicsUnit.Pixel);
                    dgvIndividualSales.Columns[11].HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Regular, GraphicsUnit.Pixel);
                    dgvIndividualSales.Columns[12].HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Regular, GraphicsUnit.Pixel);
                    dgvIndividualSales.Columns[13].HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Regular, GraphicsUnit.Pixel);
                    dgvIndividualSales.Columns[14].HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Regular, GraphicsUnit.Pixel);
                    dgvIndividualSales.Columns[15].HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Regular, GraphicsUnit.Pixel);

                    dgvIndividualSales.Focus();

                }
                else
                {
                    MessageBox.Show("No Data Available", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                Cursor.Current = Cursors.Default;
            }
            catch (Exception)
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnSaveDtls_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                bool isEntered = false;

                foreach (DataGridViewRow row in dgvIndividualSales.Rows)
                {
                    if (row.Cells["CashInHand"].Value.ToString() != string.Empty && row.Cells["CashInHand"].Value.ToString() != "0")
                    {
                        isEntered = true;
                        break;
                    }
                }

                if (isEntered)
                {
                    if (DBHelper.SaveActuals(SelectedDate, cmbBranch.SelectedValue.ToString(), dgvIndividualSales) > 0)
                    {
                        MessageBox.Show("Available Cash Saved Successfully", "Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);

                        //txtActualAmount.ReadOnly = true;
                        //btnSaveActualCash.Enabled = false;
                        //btnEditAvailableCash.Enabled = true;
                        btnFinancialReport_Click(sender, e);
                    }
                    else
                    {
                        Cursor.Current = Cursors.Default;
                        MessageBox.Show("Some unknown error has occurred.", "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    Cursor.Current = Cursors.Default;
                    MessageBox.Show("Enter Valid Values", "Invalid Values", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                Cursor.Current = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnHome_Click(object sender, EventArgs e)
        {
            tabMainCtrl.SelectTab(0);
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgvIndividualSales != null)
                {
                    Storage.CashierGrid = dgvIndividualSales;

                    NewPrinter form = new NewPrinter(lblBranch.Text, dt);
                    form.printDocument1.PrintController = new StandardPrintController();
                    form.printDocument1.Print();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        #endregion

        #region Cancelled Bills

        private void btnCancelled_Click(object sender, EventArgs e)
        {
            try
            {
                tabMainCtrl.SelectTab(2);

                dtpCancelledBills.Value = SelectedDate;

                chkCancelledBills.Checked = false;
                dgCancelledBills.DataSource = null;
                dgCancelledBillDetails.DataSource = null;
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnGetCancelledBills_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                SelectedDate = dtpCancelledBills.Value;
                bool IsException = false;

                dgCancelledBills.DataSource = DBHelper.GetCancelledBills(cmbBranchCancelledBills.SelectedValue.ToString(), dtpCancelledBills.Value, chkCancelledBills.Checked, out IsException);

                if (IsException)
                {
                    dgCancelledBills.DataSource = null;
                    dgCancelledBillDetails.DataSource = null;
                    MessageBox.Show("Some Error Has Occurred.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (dgCancelledBills.DataSource != null)
                {
                    dgCancelledBills.Columns[0].Width = 80;
                    dgCancelledBills.Columns[1].Width = 50;
                    dgCancelledBills.Columns[2].Width = 50;
                    dgCancelledBills.Columns[3].Width = 90;
                    dgCancelledBills.Columns[4].Width = 90;
                    dgCancelledBills.Columns[5].Width = 140;
                    dgCancelledBills.Columns[6].Width = 150;
                    dgCancelledBills.Columns[7].Width = 200;
                    dgCancelledBills.Columns[8].Visible = false;
                }
                else
                {
                    dgCancelledBills.DataSource = null;
                    dgCancelledBillDetails.DataSource = null;
                    MessageBox.Show("No Data Available.", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                Cursor.Current = Cursors.Default;
            }
            catch (Exception)
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dgCancelledBills_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (dgCancelledBills.SelectedRows.Count > 0)
                {
                    string billNo = dgCancelledBills.SelectedRows[0].Cells[0].Value.ToString();

                    if (billNo != string.Empty)
                    {
                        bool IsException = false;
                        dgCancelledBillDetails.DataSource = DBHelper.GetBillDetailsByBillNo(billNo, cmbBranchCancelledBills.SelectedValue.ToString(), DateTime.Parse(dgCancelledBills.SelectedRows[0].Cells[8].Value.ToString()), out IsException);

                        if (IsException)
                        {
                            dgCancelledBillDetails.DataSource = null;
                            MessageBox.Show("Some Error Has Occurred.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }

                        if (dgCancelledBillDetails.DataSource != null)
                        {
                            dgCancelledBillDetails.Columns[0].Width = 80;
                            dgCancelledBillDetails.Columns[1].Width = 80;
                            dgCancelledBillDetails.Columns[2].Width = 180;
                            dgCancelledBillDetails.Columns[3].Width = 80;
                        }
                        else
                        {
                            dgCancelledBillDetails.DataSource = null;
                            //MessageBox.Show("No Data Available.", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region Discounted Bills

        private void btnDiscounted_Click(object sender, EventArgs e)
        {
            try
            {
                tabMainCtrl.SelectTab(3);

                dtDiscount.Value = SelectedDate;

                chkDiscountMonth.Checked = false;
                dgDiscountedBills.DataSource = null;
                dgDiscountedBillDetails.DataSource = null;
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnDiscountedBills_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                SelectedDate = dtDiscount.Value;
                bool IsException = false;

                dgDiscountedBills.DataSource = DBHelper.GetDiscountedBills(cmbDiscountBranch.SelectedValue.ToString(), dtDiscount.Value, chkDiscountMonth.Checked, out IsException);

                if (IsException)
                {
                    dgDiscountedBills.DataSource = null;
                    MessageBox.Show("Some Error Has Occurred.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (dgDiscountedBills.DataSource != null)
                {
                    dgDiscountedBills.Columns[0].Width = 80;
                    dgDiscountedBills.Columns[1].Width = 50;
                    dgDiscountedBills.Columns[2].Width = 50;
                    dgDiscountedBills.Columns[3].Width = 90;
                    dgDiscountedBills.Columns[4].Width = 90;
                    dgDiscountedBills.Columns[5].Width = 100;
                    dgDiscountedBills.Columns[6].Width = 150;
                    dgDiscountedBills.Columns[7].Width = 240;
                    dgDiscountedBills.Columns[8].Visible = false;
                }
                else
                {
                    dgDiscountedBills.DataSource = null;
                    MessageBox.Show("No Data Available.", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                Cursor.Current = Cursors.Default;
            }
            catch (Exception)
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dgDiscountedBills_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (dgDiscountedBills.SelectedRows.Count > 0)
                {
                    string billNo = dgDiscountedBills.SelectedRows[0].Cells[0].Value.ToString();

                    if (billNo != string.Empty)
                    {
                        bool IsException = false;

                        dgDiscountedBillDetails.DataSource = DBHelper.GetBillDetailsByBillNo(billNo, cmbDiscountBranch.SelectedValue.ToString(), DateTime.Parse(dgDiscountedBills.SelectedRows[0].Cells[8].Value.ToString()), out IsException);

                        if (IsException)
                        {
                            dgDiscountedBillDetails.DataSource = null;
                            MessageBox.Show("Some Error Has Occurred.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        if (dgDiscountedBillDetails.DataSource != null)
                        {
                            dgDiscountedBillDetails.Columns[0].Width = 80;
                            dgDiscountedBillDetails.Columns[1].Width = 80;
                            dgDiscountedBillDetails.Columns[2].Width = 180;
                            dgDiscountedBillDetails.Columns[3].Width = 80;
                        }
                        else
                        {
                            dgDiscountedBillDetails.DataSource = null;
                            MessageBox.Show("No Data Available.", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region Cake Report

        private void btnCakeReport_Click(object sender, EventArgs e)
        {
            try
            {
                tabMainCtrl.SelectTab(4);

                dtpCakeReport.Value = SelectedDate;
                chkCakeReport.Checked = false;
                dgvBookedCakeReport.DataSource = null;
                dgvDeliveredCakeReport.DataSource = null;
                lblBkdCakeResult.Text = lblDlvCakeReport.Text = string.Empty;
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnFetchCakeReport_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                SelectedDate = dtpCakeReport.Value;
                bool IsException = false;

                //DataSet ds = DBHelper.GetCakesReport(cmbCakeBranches.SelectedValue.ToString(), dtpCakeReport.Value, chkCakeReport.Checked, chkCancelledCakes.Checked, out IsException);
                DataSet ds = DBHelper.GetCakesReport(cmbCakeBranches.SelectedValue.ToString(), dtpCakeReport.Value, chkCakeReport.Checked, cmbCakeCategory.Text, out IsException);

                if (IsException)
                {
                    dgvBookedCakeReport.DataSource = null;
                    dgvDeliveredCakeReport.DataSource = null;
                    MessageBox.Show("Some Error Has Occurred.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (ds != null)
                {
                    dgvBookedCakeReport.DataSource = ds.Tables[0];
                    dgvBookedCakeReport.Columns[0].Width = 80;
                    lblBkdCakeResult.Text = "Advance: " + ds.Tables[1].Rows[0]["Advance"].ToString() + "                " + "Qty: " + ds.Tables[1].Rows[0]["Qty"].ToString() + " Kgs";

                    dgvDeliveredCakeReport.DataSource = ds.Tables[2];
                    dgvDeliveredCakeReport.Columns[0].Width = 80;
                    lblDlvCakeReport.Text = "Balance: " + ds.Tables[3].Rows[0]["Balance"].ToString() + "                " + "Qty: " + ds.Tables[3].Rows[0]["Qty"].ToString() + " Kgs";
                }
                else
                {
                    dgvBookedCakeReport.DataSource = null;
                    dgvDeliveredCakeReport.DataSource = null;
                    MessageBox.Show("No Data Available.", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                Cursor.Current = Cursors.Default;
            }
            catch (Exception)
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region Cake Delivery Report

        private void btnCakeDeliveryReport_Click(object sender, EventArgs e)
        {
            try
            {
                tabMainCtrl.SelectTab(5);

                dtpCakeDeliveryReport.Value = SelectedDate;
                dgvUnDeliverCakeDeliveryReport.DataSource = null;
                dgvDeliverCakeDeliveryReport.DataSource = null;
                //lblBkdCakeResult.Text = lblDlvCakeReport.Text = string.Empty;
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnCakeDeliveryReportDetails_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                SelectedDate = dtpCakeDeliveryReport.Value;
                bool IsException = false;

                DataSet ds = DBHelper.GetCakesDeliveryReport(cmbCakeDeliveryReport.SelectedValue.ToString(), dtpCakeDeliveryReport.Value, out IsException);

                if (IsException)
                {
                    dgvUnDeliverCakeDeliveryReport.DataSource = null;
                    dgvDeliverCakeDeliveryReport.DataSource = null;
                    MessageBox.Show("Some Error Has Occurred.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (ds != null)
                {
                    dgvUnDeliverCakeDeliveryReport.DataSource = ds.Tables[0];
                    dgvUnDeliverCakeDeliveryReport.Columns[0].Width = 80;

                    dgvDeliverCakeDeliveryReport.DataSource = ds.Tables[1];
                    dgvDeliverCakeDeliveryReport.Columns[0].Width = 80;

                    //foreach (DataGridViewRow row in dgvUnDeliverCakeDeliveryReport.Rows)
                    //{
                    //    if (row.Cells[7].Value == null || row.Cells[7].Value.ToString() == string.Empty)
                    //    {
                    //        row.DefaultCellStyle.BackColor = Color.PaleVioletRed;
                    //    }
                    //}
                }
                else
                {
                    dgvUnDeliverCakeDeliveryReport.DataSource = null;
                    dgvDeliverCakeDeliveryReport.DataSource = null;
                    MessageBox.Show("No Data Available.", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                Cursor.Current = Cursors.Default;
            }
            catch (Exception)
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region Bulk Orders

        private void btnBulkOrders_Click(object sender, EventArgs e)
        {
            try
            {
                tabMainCtrl.SelectTab(6);

                dpDateBulk.Value = SelectedDate;
                dgMainBulk.DataSource = null;
                dgSubBulk.DataSource = null;
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnGetBulk_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                SelectedDate = dpDateBulk.Value;
                bool IsException = false;

                DataTable ds = DBHelper.GetBulkOrders(cmbBranchBulk.SelectedValue.ToString(), dpDateBulk.Value, chkMonthBulk.Checked, out IsException);

                if (IsException)
                {
                    dgMainBulk.DataSource = null;
                    dgSubBulk.DataSource = null;
                    MessageBox.Show("Some Error Has Occurred.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (ds != null)
                {
                    dgMainBulk.DataSource = ds;
                    dgMainBulk.Columns[0].Width = 80;
                    dgMainBulk.Columns[2].Width = 85;
                    dgMainBulk.Columns[3].Width = 60;
                    dgMainBulk.Columns[4].Width = 60;
                    dgMainBulk.Columns[7].Width = 70;
                    dgMainBulk.Columns[8].Width = 170;
                    dgMainBulk.Columns[9].Visible = false;
                }
                else
                {
                    dgMainBulk.DataSource = null;
                    dgSubBulk.DataSource = null;
                    MessageBox.Show("No Data Available.", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }

                Cursor.Current = Cursors.Default;
            }
            catch (Exception)
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dgMainBulk_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (dgMainBulk.SelectedRows.Count > 0)
                {
                    string billNo = dgMainBulk.SelectedRows[0].Cells[0].Value.ToString();

                    if (billNo != string.Empty)
                    {
                        bool IsException = false;

                        dgSubBulk.DataSource = DBHelper.GetBillDetailsByBillNo(billNo, cmbBranchBulk.SelectedValue.ToString(), DateTime.Parse(dgMainBulk.SelectedRows[0].Cells[9].Value.ToString()), out IsException);

                        if (IsException)
                        {
                            dgSubBulk.DataSource = null;
                            MessageBox.Show("Some Error Has Occurred.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        if (dgSubBulk.DataSource != null)
                        {
                            dgSubBulk.Columns[0].Width = 80;
                            dgSubBulk.Columns[1].Width = 80;
                            dgSubBulk.Columns[2].Width = 180;
                            dgSubBulk.Columns[3].Width = 80;
                        }
                        else
                        {
                            dgSubBulk.DataSource = null;
                            MessageBox.Show("No Data Available.", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion
    }
}